//
//  OAuthViewController.swift
//  我的微博
//
//  Created by yz on 15/9/10.
//  Copyright © 2015年 yz. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {

    // 搭建界面
    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.sharedTools.oauthUrl()))
    }
    func webViewDidStartLoad(webView: UIWebView) {
    
        SVProgressHUD.show()
        print("开始")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        print("结束")
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        // 判断是否含有回调地址
        if !urlString.hasPrefix(NetWorkTools.sharedTools.redirectUri) {
            return true
        }

        if let query = request.URL?.query where query.hasPrefix("code="){
            // 获取授权码
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
 
            // TODO:换取TOKEN
            loadAccessToken(code)
            
        }else{
            SVProgressHUD.dismiss()
            close()
        }
        
        return true
    }

    private func loadAccessToken(code:String){

        NetWorkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
        }
        
    }
    
}
